import * as vscode from "vscode";
import fs, { open } from "fs";
import os from "os";
import path from "path";

let code = `(content) => { return content; };`;

//
export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand("cal.convert", () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) return;
      const selection = editor.selection;
      const text = editor.document.getText(selection);
      const convert = eval(`(${code})`);

      editor.edit((editBuilder) => {
        editBuilder.replace(selection, convert(text));
      });
    })
  );

  const tempFilePath = path.join(os.tmpdir(), "new-js-snippet.js");
  const openPath = vscode.Uri.file(tempFilePath);

  if (!fs.existsSync(tempFilePath)) {
    fs.writeFileSync(tempFilePath, code);
  }

  const loadCode = () => {
    code = fs.readFileSync(tempFilePath).toString();
    // in case of code formatter add semicolon to the code !!!
    code = code.substring(0, code.lastIndexOf("}") + 1);

    vscode.window.showInformationMessage(code);
  };
  loadCode();

  // context.subscriptions.push(
  //   vscode.workspace.onDidSaveTextDocument(
  //     (document: vscode.TextDocument) => {
  //       if (
  //         path.normalize(document.fileName) === path.normalize(tempFilePath)
  //       ) {
  //         loadCode();
  //         console.log("reload code!");
  //       }
  //     },
  //     null,
  //     context.subscriptions
  //   )
  // );

  context.subscriptions.push(
    vscode.commands.registerCommand("cal.reload", () => {
      loadCode();
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand("cal.code", () => {
      if (fs.existsSync(tempFilePath))
        vscode.workspace.openTextDocument(openPath).then((doc) => {
          vscode.window.showTextDocument(doc).then((editor) => {
            // editor.edit((editBuilder) => {
            //   editBuilder.insert(
            //     new vscode.Position(0, 20),
            //     `(content) => { return content; };`
            //   );
            // });
          });
        });
    })
  );
}

export function deactivate() {}
